using UnityEngine.Playables;

namespace IQIGame.Onigao.GamePlay
{
    public class BattleLoopBehaviour : PlayableBehaviour
    {
        public BattleTimelineComponent timelineComp;
        private bool _previousEnableState = false;
        private PlayableDirector _director;
        private double _startTime;
        private double _duration;

        public override void OnGraphStart(Playable playable)
        {
            base.OnGraphStart(playable);
            this._director = playable.GetGraph().GetResolver() as PlayableDirector;
        }

        public override void ProcessFrame(Playable playable, FrameData info, object playerData)
        {
            if (this.timelineComp?.enableLoopClip ?? false)
            {
                if (!this._previousEnableState)
                {
                    this._startTime = this._director.time; // 保存当前时间
                    this._previousEnableState = true;
                }
                if (this._director.time >= this._startTime + playable.GetDuration())
                {
                    this.BackToStart();
                }
            }
            else
            {
                if (this._previousEnableState)
                {
                    this._director.time = this._startTime + playable.GetDuration(); // 跳到轨道末尾
                    this._previousEnableState = false;
                }
            }
        }

        public override void OnBehaviourPause(Playable playable, FrameData info)
        {
            base.OnBehaviourPause(playable, info);
            if ((this.timelineComp?.enableLoopClip ?? false) && this._previousEnableState)
            {
                this.BackToStart();
            }
        }

        private void BackToStart()
        {
            this._director.time = this._startTime; // 重置到保存的时间
            this._director.Evaluate();
        }
    }
}